﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using Adalbertus.BudgetPlanner.Domain;
using Adalbertus.BudgetPlanner.ViewModels.ExternalSources;
using Caliburn.Micro;

namespace Adalbertus.BudgetPlanner.ViewModels.BudgetPlanning
{
    public class BudgetVM : PropertyChangedBase
    {
        private readonly Budget _wrappedBudget;
        public Budget WrappedBudget
        {
            get
            {
                Contract.Ensures(Contract.Result<Budget>() != null);
                return _wrappedBudget;
            }
        }

        public BudgetVM(Budget budget)
        {
            Contract.Requires<ArgumentNullException>(budget != null);
            _wrappedBudget = budget;
            _planList = new BindableCollectionExt<BudgetPlanVM>();
            _incomes = new BindableCollection<IncomeEntryVM>();
            _savings = new BindableCollection<SavingEntryVM>();
            
            IEnumerable<BudgetPlanVM> budgetPlanItems = budget.BudgetPlanItems.Select(x => new BudgetPlanVM(x));
            PlanList.AddRange(budgetPlanItems);

            IEnumerable<IncomeEntryVM> incomes = budget.Incomes.Select(x => new IncomeEntryVM(x));
            Incomes.AddRange(incomes);
            IEnumerable<SavingEntryVM> savings = budget.Savings.Select(x => new SavingEntryVM(x) { IsWithdrawPresentationDisabled = true });
            Savings.AddRange(savings);
        }

        public DateTime DateFrom
        {
            get { return WrappedBudget.DateFrom; }
            set
            {
                WrappedBudget.DateFrom = value;
                NotifyOfPropertyChange(() => DateFrom);
            }
        }

        public DateTime DateTo
        {
            get { return WrappedBudget.DateTo; }
            set
            {
                WrappedBudget.DateTo = value;
                NotifyOfPropertyChange(() => DateTo);
            }
        }

        private BindableCollectionExt<BudgetPlanVM> _planList;
        public BindableCollectionExt<BudgetPlanVM> PlanList
        {
            get
            {
                Contract.Ensures(Contract.Result<BindableCollectionExt<BudgetPlanVM>>() != null);
                return _planList;
            }
        }

        private BindableCollection<IncomeEntryVM> _incomes;
        public BindableCollection<IncomeEntryVM> Incomes
        {
            get
            {
                Contract.Ensures(Contract.Result<BindableCollection<IncomeEntryVM>>() != null);
                return _incomes;
            }
        }

        private BindableCollection<SavingEntryVM> _savings;
        public BindableCollection<SavingEntryVM> Savings
        {
            get
            {
                Contract.Ensures(Contract.Result<BindableCollection<SavingEntryVM>>() != null);
                return _savings;
            }
        }
    }
}
